package cn.bocweb.spinning.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bocweb.spinning.R;
import cn.bocweb.spinning.model.Bean.ErrorBean;
import cn.bocweb.spinning.model.Bean.LibListBean;
import cn.bocweb.spinning.model.Bean.SecondDownloadBean;
import cn.bocweb.spinning.model.Bean.SecondEnterBean;
import cn.bocweb.spinning.model.Bean.StartExamBean;
import cn.bocweb.spinning.model.Bean.UserBean;
import cn.bocweb.spinning.presenter.Imp.UserPresenterImp;
import cn.bocweb.spinning.presenter.UserPresenter;
import cn.bocweb.spinning.util.AES256Utils;
import cn.bocweb.spinning.util.Constant;
import cn.bocweb.spinning.util.DeviceUtil;
import cn.bocweb.spinning.view.common.BaseActivity;
import cn.bocweb.spinning.view.common.GlideCircle;
import de.greenrobot.event.EventBus;

public class ReadyTestActivity extends BaseActivity implements View.OnClickListener {

    String userid, libtype;
    UserPresenter presenter;
    UserBean.DataEntity user;
    boolean isFirstMatch = false, isSecondTest = false;
    String endTime;
    Intent intent;
    List<StartExamBean.DataEntity> list;
    String second_test_id;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.ready_exam_icon)
    ImageView readyExamIcon;
    @Bind(R.id.ready_exam_nickname)
    TextView readyExamNickname;
    @Bind(R.id.ready_exam_warehouse_title)
    TextView readyExamWarehouseTitle;
    @Bind(R.id.ready_exam_address)
    TextView readyExamAddress;
    @Bind(R.id.ready_exam_warehouse_num)
    TextView readyExamWarehouseNum;
    @Bind(R.id.ready_exam_time_limit)
    TextView readyExamTimeLimit;
    @Bind(R.id.ready_exam_login_account)
    EditText readyExamLoginAccount;
    @Bind(R.id.ready_exam_login_pwd)
    EditText readyExamLoginPwd;
    @Bind(R.id.ready_exam_login_submit)
    Button readyExamLoginSubmit;
    @Bind(R.id.ready_exam_login_register)
    TextView readyExamLoginRegister;
    @Bind(R.id.ready_exam_login_forget_pwd)
    TextView readyExamLoginForgetPwd;
    @Bind(R.id.ready_exam_login_area)
    LinearLayout readyExamLoginArea;
    @Bind(R.id.ready_exam_start)
    Button readyExamStart;
    @Bind(R.id.ready_exam_total_score)
    TextView readyExamTotalScore;
    @Bind(R.id.ready_exam_request_score)
    TextView readyExamRequestScore;
    @Bind(R.id.ready_exam_edit)
    TextView readyExamEdit;
    @Bind(R.id.lib_layout)
    LinearLayout mLibLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ready_test);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);

        presenter = new UserPresenterImp();
        dialog.show();

        initIntent();
        initClickBtn();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();

        if (isSecondTest) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    SecondDownloadBean bean;
                    File cacheFile = new File(getCacheDir().getAbsolutePath() + "/secondTest.txt");
                    if (cacheFile.exists()) {
                        ObjectInputStream objectInputStream;
                        try {
                            list = new ArrayList<>();
                            intent = new Intent(ReadyTestActivity.this, TestActivity.class);
                            intent.putExtra(Constant.TO_TEST_TEST_ID, second_test_id);
                            objectInputStream = new ObjectInputStream(new FileInputStream(cacheFile));
                            bean = (SecondDownloadBean) objectInputStream.readObject();

                            for (SecondDownloadBean.DataBean dataBean : bean.getData()) {
                                StartExamBean.DataEntity exambean = new StartExamBean.DataEntity();


                                try {
                                    exambean.setId(AES256Utils.getInstance().decryptSecure(dataBean.getId()));
                                    exambean.setTitle(AES256Utils.getInstance().decryptSecure(dataBean.getTitle()));
                                    exambean.setRight(AES256Utils.getInstance().decryptSecure(dataBean.getRight()));
                                    exambean.setTtype(AES256Utils.getInstance().decryptSecure(dataBean.getTtype()));
                                    exambean.setTid(AES256Utils.getInstance().decryptSecure(dataBean.getTid()));
                                    exambean.setLibtype(AES256Utils.getInstance().decryptSecure(dataBean.getLibtype()));
                                    if (dataBean.getOption() != null) {
                                        List<String> list = new ArrayList<>();
                                        for (String s : dataBean.getOption()) {
                                            list.add(AES256Utils.getInstance().decryptSecure(s));
                                        }
                                        exambean.setOption(list);
                                    }
                                    exambean.setExplain(AES256Utils.getInstance().decryptSecure(dataBean.getExplain()));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
//
//
//
//                                exambean.setId(dataBean.getId());
//                                exambean.setExplain(dataBean.getExplain());
//                                exambean.setTid(dataBean.getTid());
//                                exambean.setTtype(dataBean.getTtype());
//                                exambean.setOption(dataBean.getOption());
//                                exambean.setRight(dataBean.getRight());
//                                exambean.setTitle(dataBean.getTitle());
//                                exambean.setLibtype(dataBean.getLibtype());

                                list.add(exambean);
                            }
                            setMyIntent(bean.getTimelimit(), bean);
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        } else {
            presenter.startExam(userid, libtype);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Constant.SET_WARE_TO_MAIN) {
            LibListBean.DataEntity dataEntity = new LibListBean.DataEntity();
            dataEntity.readLibListIntoLocal(this);
            libtype = dataEntity.getId();
            readyExamWarehouseTitle.setText(dataEntity.getTitle());
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);

        }
    }

    private void initIntent() {
        Intent intent = getIntent();
        String id = intent.getStringExtra(Constant.TO_READY_FIRST_TEST_ID);
        if (id == null || id.isEmpty()) {
            initExamInfo(false);
            isFirstMatch = false;
            initToolbar("开始考试");
        } else {
            isSecondTest = intent.getBooleanExtra(Constant.TO_SECOND_RULE_IS_SECOND_TEST, false);
            libtype = id;
            initExamInfo(true);
            isFirstMatch = intent.getBooleanExtra(Constant.TO_TEST_RANK_IF_FIRST, false);
            if (!isSecondTest) {
                readyExamWarehouseTitle.setText("梳理初赛");
                mLibLayout.setVisibility(View.VISIBLE);
                readyExamStart.setText("开始考试");
                readyExamEdit.setVisibility(View.GONE);
                initToolbar("\"金轮-蓝钻杯\"全国梳理知识大奖赛");
            } else {
//                second_test_id = intent.getStringExtra(Constant.TO_SECOND_RULE_TEST_ID);
                mLibLayout.setVisibility(View.VISIBLE);

//                readyExamWarehouseTitle.setText("梳理复赛");
//                initToolbar("\"金轮-蓝钻杯\"全国梳理知识大奖赛复赛");

                readyExamWarehouseTitle.setText("梳理决赛");
                initToolbar("\"金轮-蓝钻杯\"全国梳理知识大奖赛决赛");

                readyExamStart.setText("开始考试");
                readyExamWarehouseNum.setText("50");
                readyExamEdit.setVisibility(View.GONE);
                endTime = intent.getStringExtra(Constant.TO_SECOND_RULE_END_TIME);
                readyExamTimeLimit.setText("15");
            }
        }
    }


    public void onEventMainThread(SecondEnterBean bean) {
        if (bean.getReturn_code() == 0) {
            intent.putExtra(Constant.TO_TEST_TEST_ID, bean.getTestid());
            DeviceUtil.Log("secondEnter O = " + bean.getMsg());
            startActivity(intent);
            finish();
        } else {
            readyExamStart.setClickable(true);
            DeviceUtil.Log("secondEnter !0 = " + bean.getMsg());
            DeviceUtil.MyToast(this, bean.getMsg());
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
        }
    }

    private void initClickBtn() {
        readyExamStart.setOnClickListener(this);
        readyExamLoginSubmit.setOnClickListener(this);
        readyExamLoginRegister.setOnClickListener(this);
        readyExamLoginForgetPwd.setOnClickListener(this);
        readyExamEdit.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ready_exam_start: {

                if (intent == null) {
                    DeviceUtil.MyToast(ReadyTestActivity.this, "正在获取考题");
                } else {
                    readyExamStart.setClickable(false);
                    if (isSecondTest) {
                        presenter.secondEnter(userid);
                    } else {
                        startActivity(intent);
                        finish();
                    }
                }
                break;
            }
            case R.id.ready_exam_login_submit: {
                String phone = readyExamLoginAccount.getText().toString();
                String pwd = readyExamLoginPwd.getText().toString();
                presenter.login(phone, pwd);
                break;
            }
            case R.id.ready_exam_login_register: {
                Intent intent = new Intent(this, RegisterActivity.class);
                intent.putExtra(Constant.TO_REGISTER, Constant.READY_TEST_TO_REGISTER);
                startActivity(intent);
                break;
            }
            case R.id.ready_exam_login_forget_pwd: {
                Intent intent = new Intent(this, ForgetPwdActivity.class);
                startActivity(intent);
                break;
            }
            case R.id.ready_exam_edit: {
                Intent intent = new Intent(this, SetQuesWarehouseActivity.class);
                startActivityForResult(intent, Constant.SET_WARE_TO_MAIN);
                break;
            }
        }
    }

    private void initExamInfo(boolean isFirstMatch) {
        user = new UserBean.DataEntity();
        user.readInfoFromLocal(this);

        if (!isFirstMatch) {
            LibListBean.DataEntity liblist = new LibListBean.DataEntity();
            liblist.readLibListIntoLocal(this);
            libtype = liblist.getId();
            readyExamWarehouseTitle.setText(liblist.getTitle());
            readyExamTotalScore.setText(liblist.getTotalScore());
            readyExamRequestScore.setText(liblist.getRequireScore());
            readyExamWarehouseTitle.setText(liblist.getTitle());
            mLibLayout.setVisibility(View.VISIBLE);
        }
//        else {
//            mLibLayout.setVisibility(View.GONE);
//        }

        if (user.getUserid() == null || user.getUserid().isEmpty()) {
            readyExamLoginArea.setVisibility(View.VISIBLE);
            readyExamStart.setVisibility(View.GONE);
            readyExamIcon.setImageResource(R.mipmap.drawer_icon_unlogin);
            readyExamNickname.setText("未登录");
            readyExamAddress.setText("未登录");
        } else {
            userid = user.getUserid();
            readyExamStart.setVisibility(View.VISIBLE);
            readyExamLoginArea.setVisibility(View.GONE);
            String icon = user.getUthumb();
            String nickname = user.getNickname();
            String address = user.getAddress();

            Glide.with(this)
                    .load(icon)
                    .transform(new GlideCircle(this))
                    .placeholder(R.mipmap.drawer_icon_unlogin)
                    .into(readyExamIcon);

            if (nickname == null || nickname.isEmpty()) {
                readyExamNickname.setText(Constant.NICKNAME_UNLOGIN);
            } else {
                readyExamNickname.setText(nickname);
            }

            if (address == null || address.isEmpty()) {
                readyExamAddress.setText(Constant.ADDRESS_UNLOGIN);
            } else {
                readyExamAddress.setText(address);
            }
        }
    }

    private void initToolbar(String title) {
        toolbar.setTitle(title);
        toolbar.setTitleTextColor(getResources().getColor(R.color.white));
        toolbar.setNavigationIcon(R.mipmap.btn_exit);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    public void onEventMainThread(UserBean bean) {
        if (bean.getReturn_code() == 0) {
            user = bean.getData();
            user.writeInfoIntoLocal(this);
            Intent intent = new Intent(this, ReadyTestActivity.class);
            intent.putExtra(Constant.TO_READY_FIRST_TEST_ID, libtype);
            intent.putExtra(Constant.TO_SECOND_RULE_IS_SECOND_TEST, isSecondTest);
            startActivity(intent);
            finish();
        } else {
            DeviceUtil.MyToast(this, bean.getMsg());
        }
    }

    public void onEventMainThread(StartExamBean bean) {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
        if (bean.getReturn_code() == 0) {
            list = bean.getData();
            intent = new Intent(this, TestActivity.class);

//            intent.putExtra(Constant.START_EXAM_TIMELIMIT, bean.getTimelimit());
            setMyIntent(bean);
        } else {
            if (bean.getReturn_code() != -201) {
                DeviceUtil.MyToast(this, bean.getMsg());
            }
            readyExamTimeLimit.setText(bean.getTimelimit());
            readyExamWarehouseNum.setText(String.valueOf(bean.getSum()));
            readyExamTotalScore.setText(bean.getTotalSocre());
            readyExamRequestScore.setText(bean.getRequireScore());
        }

        readyExamStart.setClickable(true);
    }

    public void setMyIntent(StartExamBean bean) {
        intent.putExtra(Constant.START_EXAM_LIST, (Serializable) list);
        intent.putExtra(Constant.START_EXAM_LIBID, libtype);
        intent.putExtra(Constant.START_EXAM_ISFIRSTMATCH, isFirstMatch);
        intent.putExtra(Constant.START_EXAM_ISSECONDTEST, isSecondTest);
//        if (!isSecondTest) {
        intent.putExtra(Constant.START_EXAM_TESTID, bean.getTestid());
        intent.putExtra(Constant.START_EXAM_USERID, bean.getUserid());
//        }
        if (!TextUtils.isEmpty(endTime)) {
            intent.putExtra(Constant.START_EXAM_END_TIME, endTime);
        } else {
            intent.putExtra(Constant.START_EXAM_TIMELIMIT, bean.getTimelimit());
        }

        readyExamTimeLimit.setText("15");
        readyExamWarehouseNum.setText(String.valueOf(bean.getSum()));
        readyExamTotalScore.setText(bean.getTotalSocre());
        readyExamRequestScore.setText(bean.getRequireScore());
    }

    public void setMyIntent(String time, final SecondDownloadBean bean) {
        DeviceUtil.Log("list = " + list.size());
        intent.putExtra(Constant.START_EXAM_LIST, (Serializable) list);
        intent.putExtra(Constant.START_EXAM_LIBID, libtype);
        intent.putExtra(Constant.START_EXAM_ISFIRSTMATCH, isFirstMatch);
        intent.putExtra(Constant.START_EXAM_ISSECONDTEST, isSecondTest);
        if (!TextUtils.isEmpty(endTime)) {
            intent.putExtra(Constant.START_EXAM_END_TIME, endTime);
        } else {
            intent.putExtra(Constant.START_EXAM_TIMELIMIT, time);
        }


        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    readyExamWarehouseNum.setText(String.valueOf(bean.getData().size()));
                    readyExamTotalScore.setText("100");

                    readyExamTimeLimit.setText("15");
                    readyExamRequestScore.setText(AES256Utils.getInstance().decryptSecure(bean.getRequireScore()));

//                    readyExamTimeLimit.setText(bean.getTimelimit());
//                    readyExamRequestScore.setText(bean.getRequireScore());
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });
    }

    public void onEventMainThread(ErrorBean bean) {
        hideLoading();
        DeviceUtil.MyToast(this, bean.getErrorMsg());
        readyExamStart.setClickable(true);
    }
}
